import { createApp } from 'vue'
import App from './App.vue'

import router from './routers/index.js'
import request from './services/request'
import store from './store/index'
import piniaPluginPersist from 'pinia-plugin-persistedstate'//引入pinia数据持久化插件
import rules from './routers/rules'
import VueNativeSock from "vue-native-websocket-vue3";
import socketStore from './store/useSocketStore';

const app = createApp(App)
.use(router)
.use(request)
.use(createPinia().use(piniaPluginPersist)) //状态管理
.use(store)
.use(socketStore)
.use(VueNativeSock,"ws://127.0.0.1:8888",{
    "format": "json",
    "reconnection": true,
    "reconnectionAttempts": 5, 
    "reconnectionDelay": 3000,
    "connectManually": true
  })
.mount('#app')

router.beforeEach(async(to,from)=>{
    if(rules.includes(to.path))return true;
    if(app.$business.value.id!=0)return true;
    const token = localStorage.getItem('token')
    if(token){
        const result = await app.$GET({
            url:'/business/check',
            params:{token}
        })
        if(result.code==0){
            localStorage.removeItem('token')
            showFailToast({
                message: result.msg,
                duration: 1000,
            })
            return { path: '/business/login' }
        }
        app.$business.value = result.data;
        return true;
    }
    return { path: '/business/login' }
})